package com.lfs.feishu.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.lark.oapi.Client;
import com.lark.oapi.service.im.v1.model.ListChatReq;
import com.lark.oapi.service.im.v1.model.ListChatResp;
import com.lfs.feishu.domain.request.BatchSendRequest;
import com.lfs.feishu.service.UserInfoService;
import com.lfs.feishu.utils.CommonUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lark.oapi.service.im.v1.model.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;

import org.springframework.web.client.RestTemplate;

import static com.lfs.feishu.constant.AppInfo.*;

@AllArgsConstructor
@RestController
@RequestMapping("/feishu/group")
@Slf4j
public class GroupChatController {
    UserInfoService userInfoService;
    RestTemplate restTemplate;
    FeishuBatchSendController feishuBatchSendController;

    /**
     * 获取应用机器人所在的群聊
     * @return 群聊列表
     */
    @GetMapping("/chats")
    public ListChatRespBody getChats(@RequestParam(value = "pageToken",required = false) String pageToken) throws Exception {
        // 构建client
        Client client = Client.newBuilder(APP_ID, APP_SECRET).build();

        // 创建请求对象
        ListChatReq req = ListChatReq.newBuilder()
                .sortType("ByCreateTimeAsc")
                .pageToken(pageToken) //分页游标，第一次请求不用传
                .pageSize(100)
                .build();

        // 发起请求
        ListChatResp resp = client.im().v1().chat().list(req);
        return resp.getData();
    }

    /**
     * 自定义机器人发送
     */
    @GetMapping("/webhookSend")
    public void webhookSend() throws Exception {
        BatchSendRequest batchSendRequest = new BatchSendRequest();
        batchSendRequest.setUrl("https://open.feishu.cn/open-apis/bot/v2/hook/895bfa98-5ab8-4054-a49f-ce96047b7a52");
        String secret = System.getenv("SECRET");
        int timestamp = (int)(System.currentTimeMillis() / 1000L);
        String sign = CommonUtil.GenSign(secret, timestamp);

        batchSendRequest.setSign(sign);
        batchSendRequest.setTimestamp(String.valueOf(timestamp));
        feishuBatchSendController.batchSendCard(batchSendRequest);
    }

    /**
     * 创建群聊
     */
    @GetMapping("/createChat")
    public void createChat(){
        // 构建client
        Client client = Client.newBuilder(APP_ID, APP_SECRET).build();
        CreateChatReq req = CreateChatReq.newBuilder()
                .userIdType("user_id")
                .setBotManager(false)
                .uuid(UUID.randomUUID().toString())
                .createChatReqBody(CreateChatReqBody.newBuilder()
//                        .avatar("default-avatar_44ae0ca3-e140-494b-956f-78091e348435")
                        .name("这是一个测试群")
                        .description("测试群描述")
                        .ownerId("201511")
                        .userIdList(new String[]{"263143"})
//                        .botIdList(new String[]{"cli_a10fbf7e94b8d01d"})
                        .groupMessageType("chat")
                        .chatMode("group")
                        .chatType("private")
                        .joinMessageVisibility("all_members")
                        .leaveMessageVisibility("all_members")
                        .membershipApproval("no_approval_required")
                        .restrictedModeSetting(RestrictedModeSetting.newBuilder()
                                .status(false)
                                .screenshotHasPermissionSetting("all_members")
                                .downloadHasPermissionSetting("all_members")
                                .messageHasPermissionSetting("all_members")
                                .build())
                        .urgentSetting("all_members")
                        .videoConferenceSetting("all_members")
                        .editPermission("all_members")
                        .hideMemberCountSetting("all_members")
                        .build())
                .build();

        // 发起请求
        CreateChatResp resp;
        try {
            resp = client.im().v1().chat().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info("创建群聊结果：\n{}", JSONUtil.formatJsonStr(JSON.toJSONString(resp.getData())));
    }
}
